import { Request, Response } from 'express';
import { FileService } from '../services/file-service';
import { ResponseUtil } from '../utils/response';
import multer from 'multer';

// 配置multer用于处理文件上传
const storage = multer.memoryStorage();
export const upload = multer({
  storage,
  limits: {
    fileSize: 50 * 1024 * 1024,
  },
  fileFilter: (req: any, file: any, cb: any) => {
    // 修复中文文件名乱码问题
    if (file.originalname) {
      // 将文件名从latin1编码转换为utf8
      file.originalname = Buffer.from(file.originalname, 'latin1').toString('utf8');
    }
    
    console.log(
      'Uploading file:',
      file.originalname,
      'Type:',
      file.mimetype,
      'Size:',
      file.size
    );

    const allowedMimes = [
      'image/jpeg',
      'image/png',
      'image/gif',
      'application/pdf',
      'text/plain',
      'application/msword',
      'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
    ];

    if (allowedMimes.includes(file.mimetype)) {
      cb(null, true);
    } else {
      console.error('Unsupported file type:', file.mimetype);
      cb(new Error(`不支持的文件类型: ${file.mimetype}`));
    }
  },
});

export class FileController {
  /**
   * 上传单个文件
   */
  static async uploadSingle(req: Request, res: Response): Promise<void> {
    try {
      console.log('Upload request received:', {
        hasFile: !!req.file,
        fileName: req.file?.originalname,
        fileSize: req.file?.size,
        mimeType: req.file?.mimetype,
      });

      if (!req.file) {
        ResponseUtil.error(res, '请选择要上传的文件', 400);
        return;
      }

      const result = await FileService.uploadFile(
        req.file.buffer,
        req.file.originalname,
        req.file.mimetype
      );

      ResponseUtil.success(res, result, '文件上传成功');
    } catch (error) {
      console.error('File upload error:', error);
      ResponseUtil.error(res, '文件上传失败');
    }
  }

  /**
   * 上传多个文件
   */
  static async uploadMultiple(req: Request, res: Response): Promise<void> {
    try {
      if (!req.files || !Array.isArray(req.files) || req.files.length === 0) {
        ResponseUtil.error(res, '请选择要上传的文件', 400);
        return;
      }

      const uploadPromises = req.files.map(file =>
        FileService.uploadFile(file.buffer, file.originalname, file.mimetype)
      );

      const results = await Promise.all(uploadPromises);
      ResponseUtil.success(res, results, '文件上传成功');
    } catch (error) {
      console.error('Multiple file upload error:', error);
      ResponseUtil.error(res, '文件上传失败');
    }
  }

  /**
   * 获取文件URL
   */
  static async getFileUrl(req: Request, res: Response): Promise<void> {
    try {
      const { fileName } = req.params;
      const url = await FileService.getFileUrl(fileName);
      ResponseUtil.success(res, { url }, '获取文件URL成功');
    } catch (error) {
      console.error('Get file URL error:', error);
      ResponseUtil.error(res, '获取文件URL失败');
    }
  }

  /**
   * 删除文件
   */
  static async deleteFile(req: Request, res: Response): Promise<void> {
    try {
      const { fileName } = req.params;
      await FileService.deleteFile(fileName);
      ResponseUtil.success(res, null, '文件删除成功');
    } catch (error) {
      console.error('Delete file error:', error);
      ResponseUtil.error(res, '文件删除失败');
    }
  }

  /**
   * 获取文件列表
   */
  static async listFiles(req: Request, res: Response): Promise<void> {
    try {
      const { prefix } = req.query;
      const files = await FileService.listFiles(prefix as string);
      ResponseUtil.success(res, files, '获取文件列表成功');
    } catch (error) {
      console.error('List files error:', error);
      ResponseUtil.error(res, '获取文件列表失败');
    }
  }
}
